<?php
namespace app\shop\controller;
use	think\Controller;
use	think\Db;
use think\Input;
use think\Request;
//use phpMQTT;
use ElemeOpenApi\Config\Config;
use ElemeOpenApi\OAuth\OAuthClient;
use ElemeOpenApi\Api\UserService;
require("phpMQTT.php");
require("util.php");
require("MeituanData.php");





class Index extends	Controller {
   
	
    public function index(){

        //此处需要填写对应的参数
       $app_key = "ZZmkCSsJNu";
       $app_secret = "b6b99f72df9b34a052e291efe876ff8613a2f5d6";
       $sandbox = true;
       $scope = "all";
       $callback_url = "https://www.liqisheng.cn/snack/shop";
       $config = new Config($app_key, $app_secret, $sandbox);
       $client = new OAuthClient($config);

    	$code = input('code');
    	$state  = input('state');	
    	$time = date("Y-m-d H:i:s");
    	$error = input('error');
    	$error_description = input('error_description');

      $param = input('param.');
      $result = empty($param);
      $request = Request::instance();
      if ($request->method() == "GET" && $result ) {
          return  $this->fetch("authorizedInfo"); 
      }
    
      //var_dump($test);
    	
    	//用户取消授权
    	if ($error != null && $error == "access_denied" && $error_description != null && $error_description == "Authorization is cancelled.") {    	
        return  $this->fetch("oauthfail");  
    	}
    	//用户授权
        $token = $client->get_token_by_code($code, $callback_url);
        if ($token != null) {
            $data = json_encode($token);  
            $insertData = ['code'=>$code, 'state'=> $data, 'time'=>$time];
        }
        //var_dump($token);

        $user_service = new UserService($token, $config);
        $user = $user_service->get_user();
        $userId = $user->userId;
        $shopId = "";
        $shopName = "";
        foreach ($user->authorizedShops as $shop) {
           $shopId .= $shop->id . "";
           $shopName .= $shop->name . "";
        }

       $accessToken = $token->access_token;
       $refreshToken = $token->refresh_token;

		   $result = db('shop')->insertGetId($insertData);
		   
       $this->assign('userId',  $userId); 
       $this->assign('shopName', $shopName); 
       $this->assign('accessToken', $accessToken); 
       $this->assign('refreshToken', $refreshToken);
       $this->assign('shopId', $shopId);             
       return  $this->fetch("shop");	   
	  }

  


  public function test() {

    $server = "www.liqisheng.cn";     // change if necessary
    $port = 1883;                     // change if necessary
    $username = "public";                   // set your username
    $password = "admin";                   // set your password
    $client_id = "1234545"; 
    $mqtt = new phpMQTT($server, $port, $client_id);

    $username = input('username');
    $password  = input('password'); 
    $deveiceId = input('deveiceId');
    $beginTime = date("Y-m-d H:i:s");

    $map['username'] = $username;
    $map['password'] = $password;
    $user = db('user')->where($map)->select();

    if ($user == null) {
      return  json(['message'=>"user not exit", 'code'=>201]) ;  
      exit();
    }

    $userId = $user[0]["id"];

    $loginInfo = Db::table('loginfo')
                   ->where('userId',$userId)
                   ->select(); 

    $pushId;
    if ($loginInfo != null) {
        $pushId = $loginInfo[0]["deviceId"];
        db('loginfo')->where('userId',$userId)->delete();
    }
    $insertData = ['userId'=>$userId, 'token'=> "11", 'deviceId'=>$deveiceId, 'beginTime'=>$beginTime];
    $result = db('loginfo')->insertGetId($insertData);

    if ($pushId != null) {
        if ($mqtt->connect(true, NULL, $username, $password)) {
            $mqtt->publish($pushId, "Hello World! at " . date("r"), 0);
             $mqtt->close();
        } 
    }
    return  json(['message'=>"login success", 'code'=>200]) ;  

  }


  public function order() {


    $app_key = "ZZmkCSsJNu";
    $app_secret = "b6b99f72df9b34a052e291efe876ff8613a2f5d6";
    $sandbox = true;
    $config = new Config($app_key, $app_secret, $sandbox);


    $request = Request::instance();
    if ($request->method() == "GET") {
      return  json(['message'=>"ok"]);
      exit();
    }

    $json = file_get_contents('php://input');
    $message = convert_to_message($json);

    //校验签名
    $result = check_signature($message, $config->get_app_secret());
    if ($result == false) {
        throw new Exception("invalid signature");
    }


    $elemeResult = json_decode($json,true);
    $pushId = "eleme_" .strval($elemeResult["shopId"]);

    $server = "www.liqisheng.cn";     // change if necessary
    $port = 1883;                     // change if necessary
    $username = "public";                   // set your username
    $password = "admin";                   // set your password
    $client_id = "1234545"; 
    $mqtt = new phpMQTT($server, $port, $client_id);

    if ($mqtt->connect(true,NULL,$username,$password)) {
      $mqtt->publish($pushId, $json, 0);
      $mqtt->close();   
      return  json(['message'=>"ok"]) ;      
    }

  }


  public function crash() {

    $crashInfo = input('crashInfo');
    $insertData = ['crash_info'=>$crashInfo];
    $result = db('crash')->insertGetId($insertData);

  }



  public function testUrl() {

    return  json(['message'=>"user not exit",'time'=>"2018-01-22", 'code'=>201]) ;  

  }


  public function meituanOrderTest() {

    $server = "www.liqisheng.cn";     // change if necessary
    $port = 1883;                     // change if necessary
    $username = "public";                   // set your username
    $password = "admin";                   // set your password
    $client_id = "1234545"; 
    $mqtt = new phpMQTT($server, $port, $client_id);

    

    $json =  Request::instance()->param('order');
    $orderJson = urldecode($json);
    $ePoiId = Request::instance()->param('ePoiId');
    $pushId = "meituan_1000110";

  

    if ($mqtt->connect(true,NULL,$username,$password)) {
      $jsonObject = new MeituanResult();
      $jsonObject->data  = $orderJson;
      $jsonObject->type = 1;
      $jsonObject->ePoiId = $ePoiId;

      $json_string = json_encode($jsonObject);

      $mqtt->publish($pushId, $json_string, 0);
      $mqtt->close();   
      return  json(['data'=>"OK"]) ;      
    }

  }





  //接单
  public function meituanConfirmOrder() {

    $server = "www.liqisheng.cn";     // change if necessary
    $port = 1883;                     // change if necessary
    $username = "public";                   // set your username
    $password = "admin";                   // set your password
    $client_id = "1234545"; 
    $mqtt = new phpMQTT($server, $port, $client_id);

    //$pushId = "meituan_1000110";

    $json =  Request::instance()->param('order');
    $orderJson = urldecode($json);
    $ePoiId = Request::instance()->param('ePoiId');
    $pushId = "meituan_1000110";
  

    if ($mqtt->connect(true,NULL,$username,$password)) {
      $jsonObject = new MeituanResult();
      $jsonObject->data  = $orderJson;
      $jsonObject->type = 2;
      $jsonObject->ePoiId = $ePoiId;

      $json_string = json_encode($jsonObject);

      $mqtt->publish($pushId, $json_string, 0);
      $mqtt->close();   
      return  json(['data'=>"OK"]) ;      
    }

  }




  //取消订单
  public function meituanCancelOrder() {

    $server = "www.liqisheng.cn";     // change if necessary
    $port = 1883;                     // change if necessary
    $username = "public";                   // set your username
    $password = "admin";                   // set your password
    $client_id = "1234545"; 
    $mqtt = new phpMQTT($server, $port, $client_id);

    //$pushId = "meituan_1000110";

    $json =  Request::instance()->param('orderCancel');
    $orderJson = urldecode($json);
    $ePoiId = Request::instance()->param('ePoiId');
    $pushId = "meituan_1000110";

    if ($mqtt->connect(true,NULL,$username,$password)) {
      $jsonObject = new MeituanResult();
      $jsonObject->data  = $orderJson;
      $jsonObject->type = 3;
      $jsonObject->ePoiId = $ePoiId;

      $json_string = json_encode($jsonObject);

      $mqtt->publish($pushId, $json_string, 0);
      $mqtt->close();   
      return  json(['data'=>"OK"]) ;      
    }

  }



  //订单配送
  public function orderShipping() {


    $server = "www.liqisheng.cn";     // change if necessary
    $port = 1883;                     // change if necessary
    $username = "public";                   // set your username
    $password = "admin";                   // set your password
    $client_id = "1234545"; 
    $mqtt = new phpMQTT($server, $port, $client_id);

    //$pushId = "meituan_1000110";

    $json =  Request::instance()->param('shippingStatus');
    $orderJson = urldecode($json);
    $ePoiId = Request::instance()->param('ePoiId');
    $pushId = "meituan_1000110";

    if ($mqtt->connect(true,NULL,$username,$password)) {
      $jsonObject = new MeituanResult();
      $jsonObject->data  = $orderJson;
      $jsonObject->type = 4;
      $jsonObject->ePoiId = $ePoiId;

      $json_string = json_encode($jsonObject);

      $mqtt->publish($pushId, $json_string, 0);
      $mqtt->close();   
      return  json(['data'=>"OK"]) ;      
    }

  }



	
    
}
